package com.siecom.transport.handler;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import com.siecom.constconfig.ConstDefine;
import com.siecom.framework.device.SiecomDevice;
import com.siecom.hostservice.HKBaseApplication;
import com.siecom.hostservice.MainActivity;
import com.siecom.module.DeviceInterface;
import com.siecom.proto.Message;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhq on 2017/2/4.
 */

public class OtherHandler implements ServiceHandler {
    private static final String TAG = OtherHandler.class.getSimpleName();
    private CommServer server;
    private static ExecutorService threadPool = Executors.newFixedThreadPool(1);
    public volatile  boolean flag = false;

    @Override
    public void onReceive(CommServer server, Message.siecomproto msg,String message) {
        this.server = server;
        switch (msg.getCmd()){
            case ConstDefine.DEVICE_SERIAL_NO_REQUEST:
                getDeviceId(msg);
                break;
            case ConstDefine.CODENAME_REQUEST:
                setCodeName(msg);
                break;
            case ConstDefine.GET_CODENAME_REQUEST:
                getCodeName(msg);
                break;
            case ConstDefine.RESET_REQUEST:
                reset(msg);
                break;

            case ConstDefine.START_LAUNCHER_REQUEST:

                startLauncher(msg);
                break;

            case ConstDefine.LIGHT_TEST_REQUEST:
                testLight(msg);
                break;

            case ConstDefine.PSAM_TEST_REQUEST:
//                testPsam(msg);
                break;
            case ConstDefine.SERIAL_TEST_REQUEST:

                testSerial(msg);

                break;

            case ConstDefine.CHANGE_BLUE_NAME:
                changeBlueName(msg);
                break;
            case ConstDefine.DISCONNECT_BLUE:
                LogUtil.e(TAG,"DISCONNECT_BLUE");
                disconnectBlue(msg);
                break;
            case ConstDefine.GET_BATTARY_INFO_REQUEST:
                getBattaryInfo(msg);
                break;
                //检测各模块信息
            case ConstDefine.CHECK_MODULE_INFO_REQUEST:
                checkModules(msg);
                break;

            case ConstDefine.MAKE_BEEP_REQUEST:
                make_beep(msg);
                break;
        }
    }
    public void checkModules(Message.siecomproto msg ){  //beep
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String inModule = "";
                String modules[] = null;
                String respond = "";
                try {
                    JSONObject jb = new JSONObject(msg.getRequest());
                    if(jb.has("moduleName")){
                        inModule = jb.getString("moduleName");
                    }else {
                        inModule = "";
                    }
                    if (inModule != null){
                        JSONObject outJson = new JSONObject();
                         modules = inModule.split(":");
                         outJson.put("state",0);
                        for (String mod : modules){

                            if(mod.equals("CR")){ //读卡器
                                outJson.put("CR",0);
                            }
                            if(mod.equals("FR")){ //指纹仪
                                outJson.put("FR",0);
                            }
                            if(mod.equals("SR")){ //签名板
                                outJson.put("SR",0);
                            }
                            if(mod.equals("MR")){ //磁条卡
                                outJson.put("MR",0);
                            }
                            if(mod.equals("PR")){ //密码键盘
                                outJson.put("PR",0);
                            }
                        }
                        respond = outJson.toString();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHECK_MODULE_INFO_RESPOND);
                msgBuilder.setError(0);
                msgBuilder.setRespond(respond);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(runnable);
    }
    public void disconnectBlue(Message.siecomproto msg){
        LogUtil.e(TAG,"disconnectBlue");
//        SiecomDevice.closeBT();
        MainActivity.disconnectBlue();
//        HKBaseApplication.finishAllActivity();
//        HKBaseApplication.finishProgram();
        SiecomDevice.disConnectBtDevice();
    }
    public void make_beep(Message.siecomproto msg ){  //beep
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                SiecomDevice.beep();
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.MAKE_BEEP_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(runnable);
    }

    public void changeBlueName(Message.siecomproto msg ){  //修改蓝牙名称
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                DeviceInterface.changeBlueName(msg.getRequest());
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHANGE_BLUE_NAME);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(runnable);
    }
    /**
     * 获取电池信息
     * @param msg
     */
    private void getBattaryInfo(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_BATTARY_INFO_RESPOND);
                msgBuilder.setError(0);
                msgBuilder.setRespond(MainActivity.mBattaryInfoJB.toString());
                LogUtil.e(TAG,"发送电池状态:" + MainActivity.mBattaryInfoJB.toString());
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);
            }
        };
        threadPool.submit(r);
    }

    public  void testSerial(Message.siecomproto msg){

    }
    public  void testLight(Message.siecomproto msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if(msg.getRequest().equals("-1") || msg.getRequest().equals("")){
                    DeviceInterface.lightCtrl();
                }else {
                    int led = Integer.parseInt(msg.getRequest());
                    int onOff = Integer.parseInt(msg.getRespond());
                    DeviceInterface.lightCtrl(led,onOff);
                }
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.LIGHT_TEST_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };

        threadPool.submit(runnable);


    }
    private void testPsam(Message.siecomproto msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int tmp = Integer.valueOf(msg.getRequest());
                byte solt = 0x01;
                if(tmp==1){
                    solt = 0x01;
                }else if(tmp==2){
                    solt = 0x02;
                }
                int ret = DeviceInterface.testPsamSlot(solt);
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.PSAM_TEST_RESPOND);
                msgBuilder.setError(ret);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };

        threadPool.submit(runnable);


    }
    private void startLauncher(Message.siecomproto msg) {
        Runnable r = new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                ComponentName cn = new ComponentName("com.android.launcher3", "com.android.launcher3.Launcher");
                intent.setComponent(cn);
                MainActivity.context.startActivity(intent);

                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.START_LAUNCHER_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);
    }
    private void reset(Message.siecomproto msg) {
        Runnable r = new Runnable() {
            @Override
            public void run() {

                DeviceInterface.cancelFinancial();
                DeviceInterface.cancelIdentity();
                DeviceInterface.cancelFingerPrint();
//                DeviceInterface.cancelKeyBoardInput();

//                DeviceInterface.allClose();
//                DeviceInterface.allOpen();

                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.RESET_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);


            }
        };
        threadPool.submit(r);
    }

    public void getCodeName(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_CODENAME_RESPOND);
                msgBuilder.setError(0);
//                msgBuilder.setRespond(DeviceInterface.getValue("key"));
                msgBuilder.setRespond(DeviceInterface.getSerialCode());
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);


    }
    public  void setCodeName(Message.siecomproto msg){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                DeviceInterface.setKeyValue("key",msg.getRequest());
                DeviceInterface.setSerialCode(msg.getRequest());  //写入SN编号
                Message.siecomproto.Builder msgBuilder = com.siecom.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(msg.getMsgid());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CODENAME_RESPOND);
                msgBuilder.setError(0);
                Message.siecomproto respondMsg = msgBuilder.build();
                server.sendToRemote(respondMsg);

            }
        };
        threadPool.submit(r);

    }

    /**
     *  @return UID(String) 序列号
     *      * companyID(String) 厂商名称
     *      * SN 设备编号
     *      * Code(int) 状态码，成功返回 0，失败返回对应错误码
     * @param
     */
   public void getDeviceId(Message.siecomproto msg){

       Runnable r = () -> {
           String deviceId =   DeviceInterface.getDeviceId();
           String serialNo = Build.SERIAL;
           LogUtil.e(TAG,"Build.SERIAL = " + Build.SERIAL);
           JSONObject jb = new JSONObject();
           try {
               jb.put("code",0);
               jb.put("UID",deviceId);
               jb.put("companyID","ZBK");
               jb.put("SN",serialNo);
           } catch (JSONException e) {
               e.printStackTrace();
           }
//               String deviceId =   DeviceInterface.getDeviceVersion();
           Message.siecomproto.Builder msgBuilder = Message.siecomproto.newBuilder();
           msgBuilder.setMsgid(msg.getMsgid());
           msgBuilder.setModule(ConstDefine.OTHER_MODULE);
           msgBuilder.setCmd(ConstDefine.DEVICE_SERIAL_NO_RESPOND);
           msgBuilder.setRespond(jb.toString());
           msgBuilder.setError(0);
           Message.siecomproto respondMsg = msgBuilder.build();
           server.sendToRemote(respondMsg);
       };
       threadPool.submit(r);

   }


}
